package com.duan.laugh.starter.email;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import javax.sql.DataSource;
import java.util.List;

/**
 * 邮箱自动配置
 *
 * @author duanjw
 */
@Configuration
@EnableConfigurationProperties({EmailProperties.class})
public class EmailAutoConfiguration {
    /**
     * redis中的邮箱账户
     *
     * @return
     */
    @Bean
    public RedisEmailAccountRepository redisEmailAccountDefinitionRepository(RedisConnectionFactory redisConnectionFactory) {
        return new RedisEmailAccountRepository(redisConnectionFactory);
    }

    /**
     * 内存中的邮箱账户
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(EmailAccountRepository.class)
    public InMemoryEmailAccountRepository inMemoryMailAccountStore() {
        return new InMemoryEmailAccountRepository();
    }

    /**
     * jdbc的邮箱账户初始化到存储器里
     *
     * @param dataSource
     * @param emailAccountRepository
     * @return
     */
    @Bean
    public InitJdbcEmailAccount2Repository initJdbcEmailAccount2Repository(DataSource dataSource, EmailAccountRepository emailAccountRepository) {
        return new InitJdbcEmailAccount2Repository(dataSource, emailAccountRepository);
    }

    /**
     * 配置文件中的邮箱账户
     *
     * @param emailProperties
     * @return
     */
    @Bean
    public PropertiesEmailAccountLocator propertiesEmailAccountLocator(EmailProperties emailProperties) {
        return new PropertiesEmailAccountLocator(emailProperties);
    }


    /**
     * 邮箱账户定位器，包括所有的邮箱定位器
     *
     * @param emailAccountLocators
     * @return
     */
    @Bean
    @Primary
    public EmailAccountLocator emailAccountLocator(
            List<EmailAccountLocator> emailAccountLocators) {
        return new CompositeEmailAccountLocator(emailAccountLocators);
    }
}
